package com.cuit.zuke.product.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuit.zuke.common.util.Result;
import com.cuit.zuke.product.model.entity.Goods;
import com.cuit.zuke.product.model.vo.GoodsQueryVO;
import com.cuit.zuke.product.service.GoodsService;
import com.cuit.zuke.product.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/product/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    /**
     * 带条件分页查询
     * @param page
     * @param limit
     * @param goodsQueryVO
     * @return
     */
    @GetMapping(value = "list/{page}/{limit}")
    public Result listGoods(@PathVariable Integer page,
                            @PathVariable Integer limit,
                            GoodsQueryVO goodsQueryVO){

        Page<Goods> page1 = new Page<>(page,limit);
        Long goodsId = goodsQueryVO.getGoodsId();
        String goodsName = goodsQueryVO.getGoodsName();
        Integer goodsType = goodsQueryVO.getGoodsType();
        Byte goodsStatus = goodsQueryVO.getGoodsStatus();

        //构建查询条件
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(goodsId)){
            wrapper.eq("goods_id",goodsId);
        }
        if(!StringUtils.isEmpty(goodsStatus)){
            wrapper.eq("goods_status",goodsStatus);
        }
        if(!StringUtils.isEmpty(goodsName)){
            wrapper.like("goods_name",goodsName);
        }
        if(!StringUtils.isEmpty(goodsType)){
            wrapper.like("goods_type",goodsType);
        }

        Page<Goods> goodsPage = goodsService.selectPage(page1,wrapper);
//        // 从数据库中得到文件路径，在静态资源文件中读取并转为base64格式传给前端
//        goodsPage.setRecords(handleGoodsImg(goodsPage.getRecords()));

        return Result.ok().put("data",goodsPage);
    }

    /**
     * 分页查询
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "listf/{page}/{limit}")
    public List listGoods1(@PathVariable Integer page,
                            @PathVariable Integer limit){

        Page<Goods> page1 = new Page<>(page,limit);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_status",1);
        Page<Goods> goodsPage = goodsService.selectPage(page1,queryWrapper);
        return goodsPage.getRecords();
    }


    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    @PostMapping(value = "deleteById")
    public Result deleteGoods(@RequestBody Long id){
        boolean flag = goodsService.deleteById(id);
        if (flag){
            return Result.ok();
        }else {
            return Result.error("删除失败");
        }
    }

    /**
     *  根据id获取商品
     * @param id
     * @return
     */
    @GetMapping(value = "findById/{id}")
    public Result findById(@PathVariable Long id){
        Goods goods = goodsService.getById(id);
//        goods.setGoodsImage(getBase64(goods));
        if (goods == null){
            return Result.error("不存在该商品");
        }else {
            return Result.ok().put("data",goods);
        }
    }

    /**
     * 修改商品
     * @param goods
     * @return
     */
    @PostMapping(value = "updateGoods", produces = "application/json;")
    public Result update(@RequestParam("goods") String goods, @RequestParam(value = "filedata",required = false) MultipartFile imgFile) throws IOException {

        Goods goods1 = JSONObject.parseObject(goods, Goods.class);
        System.out.println(goods1);
        if (imgFile == null){
            boolean flag = goodsService.updateGoods(goods1);
        }else {
            boolean flag = goodsService.updateGoodsAndImgFile(goods1, imgFile);
        }
        return Result.ok();
    }

    /**
     *     根据id修改status
     */
    @GetMapping("updateGoodsStatus/{id}/{status}")
    public Result updateHospStatus(@PathVariable Long id,
                                   @PathVariable Integer status){
        goodsService.updateStatus(id,status);
        return Result.ok();
    }

    /**
     * 添加商品
     */
    @PostMapping(value = "addGoods", produces = "application/json;")
    public Result addGoods(Goods goods, @RequestParam("filedata") MultipartFile imgFile) throws IOException {
        // 保存图片并返回生成的图片名
        String fileName = FileUtil.saveFile(imgFile, new ApplicationHome(this.getClass()));
        goods.setGoodsImage(fileName);
        Integer statue = 0;
        goods.setGoodsStatus(statue.byteValue());
        goodsService.add(goods);
        return Result.ok();
    }

    /**
     * 导出excel
     */
    @GetMapping(value = "exportData")
    public void exportData(HttpServletResponse response){
        goodsService.exportGoodsData(response);
    }

    /**
     * 导入excel
     */
    @PostMapping(value = "importData")
    public Result importDict(MultipartFile file){
        goodsService.importGoodsFile(file);
        return Result.ok();
    }

    /**
     * 将 文件名转换为base64格式
     * @param records
     * @return
     */
    private List<Goods> handleGoodsImg(List<Goods> records){
        for (int i=0;i<records.size();i++){
            Goods goods = records.get(i);
            String fileName = goods.getGoodsImage();
            String path = FileUtil.getStaticImgPath(new ApplicationHome(this.getClass()));
            String base64Img = FileUtil.encryptToBase64(path + File.separator + fileName);
            goods.setGoodsImage(base64Img);
        }
        return records;
    }

    private String getBase64(Goods goods){
        String fileName = goods.getGoodsImage();
        String path = FileUtil.getStaticImgPath(new ApplicationHome(this.getClass()));
        String base64Img = FileUtil.encryptToBase64(path + File.separator + fileName);
        return base64Img;
    }

    /**
     * client 根据id的list获取商品
     */
    @PostMapping(value = "findByIdClis")
    List<Goods> findByIdClis(@RequestBody List<Long> goodsIds){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("goods_id",goodsIds);
        List<Goods> list = goodsService.list(queryWrapper);
        return list;
    }

    /**
     * client 根据id获取商品
     */
    /**
     *  根据id获取商品
     * @param id
     * @return
     */
    @GetMapping(value = "findByIdCli/{id}")
    public Goods findByIdCli(@PathVariable Long id){
        Goods goods = goodsService.getById(id);
        return goods;
    }

    /**
     * 前台首页商品展示(5个)
     */
    @GetMapping(value = "findByIdIndex")
    public List<Goods> findByIdIndex(){
        List<Long> ids = new ArrayList<>();
        ids.add(1L);
        ids.add(3L);
        ids.add(6L);
        ids.add(8L);
        ids.add(10L);
        List<Goods> goods = goodsService.getBaseMapper().selectBatchIds(ids);
        return goods;
    }

}
